const db = require('../model')
const Medicine = db.medicine
const Op = db.Sequelize.Op

// 查询所有药品
exports.findAll = async (req, res) => {
	const { page, pageSize, medCategory } = req.query
	const where = {}
	where.medWebon = 1
	if (medCategory !== '') {
		where.medCategory = medCategory
	}
	const { count, rows } = await Medicine.findAndCountAll({
		attributes: ['medInfoId', 'medName', 'medPrice'],
		where,
		limit: pageSize * 1,
		offset: pageSize * (page - 1) * 1,
		raw: true,
	})
	if (count === 0) {
		return res.status(403).send({
			code: -1,
			message: '目前没有药品上架',
		})
	}
	return res.send({
		code: 1,
		data: rows,
		count,
	})
}

// 模糊搜索
exports.search = async (req, res) => {
	const { ordName, page, pageSize, serName: medName } = req.query
	const { count, rows } = await Medicine.findAndCountAll({
		raw: true,
		where: {
			medName: {
				// 模糊查询
				[Op.like]: '%' + medName + '%',
			},
		},
		attributes: ['medInfoId', 'medName', 'medPrice'],
	})
	return res.send({
		code: 1,
		count,
		data: rows,
	})
}

// crud  操作 增删查改
//一张表里面一个controller
// 查询某个药品的详细信息
exports.findOne = async (req, res) => {
	const medInfoId = req.params.medInfoId
	const data = await Medicine.findOne({
		where: { medInfoId },
		raw: true,
	})
	if (!data) {
		return res.status(404).send({
			code: -1,
			message: '没有改药品的详细信息',
		}) //一定要return
	}
	return res.status(200).send({
		data,
	})
}
//postman测试接口 一定要跑服务器
// 新增药品
exports.createOne = async (req, res) => {
	const {
		medInfoId,
		YPID,
		medName,
		medManufacture,
		medPrice,
		medRealon,
		medWebon,
		medRx,
		medMain,
		medContain,
		medSuitable,
		medWarning,
		medUsage,
		medAdr,
	} = req.query
	console.log(
		userId,
		userName,
		userRealname,
		userPassword,
		userPhone,
		userPlace,
		userIdentity,
		userSex
	)
	const createData = UsersModel.create({
		medInfoId,
		YPID,
		medName,
		medManufacture,
		medPrice,
		medRealon,
		medWebon,
		medRx,
		medMain,
		medContain,
		medSuitable,
		medWarning,
		medUsage,
		medAdr,
	})
	createData = await createData.save()
	if (!createData) {
		return res.status(404).end() //一定要return
	}
	return res.status(200).send({
		data, //和前端对应code
	})
}
//更新药品信息
exports.update = async (req, res) => {
	const {
		medInfoId,
		medPrice,
		medPricenew,
		medRealon,
		medRealonnew,
		medWebon,
		medWebonnew,
	} = req.query
	const updateData = await Medicine.findOne({
		where: { medInfoId, medPrice, medRealon, medWebon },
	})
	updateData.medPrice = medPricenew
	updateData.medRealon = medRealonnew
	updateData.medWebon = medWebonnew
	updateData.save()
	if (!updateData) {
		return res.status(404).end()
	}
	return res.status(200).send({
		data,
	})
}
//删除药品信息
exports.delete = async (req, res) => {
	const { medInfoId } = req.query
	const deleteData = await Medicine.findOne({
		where: { medInfoId },
	})
	await deleteData.destroy()
	if (!deleteData) {
		return res.status(404).end() //一定要return
	}
	return res.status(200).send({
		data, //和前端对应code
	})
}
